package com.songcha.library_business.handler.home_dialog

import android.app.Activity
import android.content.Context
import com.songcha.library_business.R
import com.songcha.library_business.bean.configuration.SystemConfigurationResultBean
import com.songcha.library_business.proxy.configuration.SystemConfigurationManager
import com.songcha.library_common.util.PackageUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class AppUpdateDialog(context: Context):AbsHomeDialog(context) {
    private var mSystemConfigurationResultBean:SystemConfigurationResultBean?=null

    override fun getPriority(): Int {
        return 999
    }

    override fun needShowDialog(): Observable<Boolean> {
        return Observable.create{
            SystemConfigurationManager.getSystemConfiguration()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({data->
                    try{
                        if(data==null || data.appVersion==null) return@subscribe
                        mSystemConfigurationResultBean=data
                        val curVersionCode= PackageUtil.getPackageVersionCode(context)
                        val needShowDialog=(data.appVersion.showUpdate && curVersionCode<data.appVersion.newestVersion.versionCode)
                        it.onNext(needShowDialog)
                        it.onComplete()
                    }catch (e:Exception){
                        e.printStackTrace()
                        it.onError(e)
                    }
                },{

                })
        }
    }

    override fun showDialog() {
        if(mSystemConfigurationResultBean==null) return
        if(context !is Activity) return
        val curVersionCode=PackageUtil.getPackageVersionCode(context)
        val manager = com.azhon.appupdate.manager.DownloadManager.Builder(context).run {
            apkUrl(mSystemConfigurationResultBean!!.appVersion!!.newestVersion.downloadUrl)
            apkName(PackageUtil.getPackageName(context)+".apk")
            smallIcon(R.mipmap.business_logo)
            //if set this argument,then internal will auto determine whether need to show update dialog,
            //otherwise need to determine by self
            apkVersionCode(mSystemConfigurationResultBean!!.appVersion!!.newestVersion.versionCode)
            //below argument need to set simultaneous
            apkVersionName(mSystemConfigurationResultBean!!.appVersion!!.newestVersion.versionName)
            apkSize(mSystemConfigurationResultBean!!.appVersion!!.newestVersion.packageSize)
            apkDescription(mSystemConfigurationResultBean!!.appVersion!!.newestVersion.updateContent)
            forcedUpgrade(curVersionCode<mSystemConfigurationResultBean!!.appVersion!!.lowestVersion.versionCode)
            build()
        }
        manager?.download()
    }
}